package com.czk.classreader.method;

import com.czk.utils.FileUtil;
import org.objectweb.asm.*;

import static org.objectweb.asm.Opcodes.*;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/8/6 16:40
 */
public class ClassMethodAddCore {
    public static void main(String[] args) {
        String path = "F:\\IdeaProjects\\asm\\target\\classes\\com\\czk\\sample\\Test.class";
        byte[] bytes1 = FileUtil.readBytes(path);
        // read
        ClassReader cr = new ClassReader(bytes1);
        // write
        ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
        // 串联classVisitor
        int api = Opcodes.ASM9;
        // 自己改变版本说的实现类
        ClassVisitor cv = new ClassAddMethodVisitor(api, cw, Opcodes.ACC_PUBLIC, "add", "(II)I", null, null) {
            @Override
            public void generateMethodBody(MethodVisitor mv) {
                mv.visitCode();
                mv.visitVarInsn(ILOAD, 1);
                mv.visitVarInsn(ILOAD, 2);
                mv.visitInsn(IMUL);
                mv.visitInsn(IRETURN);
                mv.visitMaxs(2, 3);
                mv.visitEnd();
            }
        };
        int parsingOptions = ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES;
        // 连接
        cr.accept(cv, parsingOptions);
        // 字节
        byte[] bytes = cw.toByteArray();
        // 写出
        FileUtil.writeBytes(path, bytes);
    }
}
